<template>
    <AdminSkeleton>
        <template #header>
            <div class="params">
                <el-form label-width="auto">
                    <el-form-item>
                        <el-button type="primary" size="small" @click="getDatas" :loading="loading">查询</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </template>
        <template #control>
            <Control :batchIsShow="batchIsShow" :downloadBoxShow="downloadBoxShow" :permObj="permObj"
                @addClick="editDatas('add', {})" @showDownload="showDownloadBox"
                @downloadExcelPaging="downloadExcelPaging(newDatasArr, 'contentTable', '标签值信息')"
                @downloadExcelAll="downloadExcelAll(datasArr, '标签值信息')" @batchToggleShow="batchEdit"
                @batchDel="editSubmit('batchDel', selectRows)" @batchUpload="batchUpload"></Control>
            <Paging :dataLength="datasLength" :countPage="countPage" :btnDisabledObj="btnDisabledObj"
                v-model:firstPage="firstPage" v-model:pageSize="pageSize" @toNext="nextPage(firstPage)"
                @toLast="lastPage(firstPage)" @toFirst="toFirstPage" @toEnd="toEndPage" @toSpecify="toSpecifyPage"
                @changePsize="changePageSize"></Paging>
        </template>
        <template #content>
            <el-table :data="newDatasArr" style="width: 100%" v-loading="loading"
                @selection-change="handleSelectionChange" id="contentTable">
                <el-table-column type="selection" width="50" v-if="selectShow" />
                <el-table-column prop="V_NUM" label="ID" width="70" />
                <el-table-column prop="VALUE" label="值" width="120" />
                <el-table-column prop="DESCRIPTION" label="描述" width="120" />
                <el-table-column prop="CUST_TYPE" label="类型" width="150" />
                <el-table-column fixed="right" label="Operations" min-width="180"
                    v-perm="permObj.update"
                >
                    <template #default="{row}">
                        <el-button type="primary" size="small" 
                            @click="editDatas('update',row)" title="编辑"
                            v-perm="permObj.update"
                        >
                            <el-icon><Edit /></el-icon>
                        </el-button>
                        <el-button type="warning" size="small" 
                            @click="editDatas('copy',row)" title="复制"
                            v-perm="permObj.add"
                        >
                            <el-icon><CopyDocument /></el-icon>
                        </el-button>
                        <el-button  type="danger" size="small" class="del" title="删除" 
                            @click="editSubmit('delete',row)"
                            v-perm="permObj.delete"
                        >
                            <el-icon><DeleteFilled /></el-icon>
                        </el-button>
                    </template>
                </el-table-column>  
            </el-table>
        </template>
    </AdminSkeleton>
    <Drawer ref="drawerRef" :title="title" :size="size" @submit="editSubmit(submitType, editForm)"
        @cancel-submit="resetForm">
        <el-form :model="editForm"  
            ref="updateFormRef"
            :rules="rules"
        >
            <el-form-item label="ID" :label-width="formLabelWidth">
                <el-input v-model="editForm.V_NUM" autocomplete="off" disabled/>
            </el-form-item>
            <el-form-item label="值" :label-width="formLabelWidth" prop="VALUE">
                <el-input v-model="editForm.VALUE" autocomplete="off" />
            </el-form-item>
            <el-form-item label="描述" :label-width="formLabelWidth" prop="DESCRIPTION">
                <el-input v-model="editForm.DESCRIPTION" autocomplete="off" />
            </el-form-item>
            <el-form-item label="类型" :label-width="formLabelWidth" prop="CUST_TYPE">
                <el-input v-model="editForm.CUST_TYPE" autocomplete="off" />
            </el-form-item>
      </el-form>
    </Drawer>
    <Dialog ref="dialogRef" :uploadKeys="uploadKeys" @uploadFile="uploadFile" @closeDialog="closeDialog"
        @batchUpdate="editSubmit('batchUpdate', uploadTable)" @batchAdd="editSubmit('batchAdd', uploadTable)"
        @downloadTemplate="downloadTemplate('upload-table', '标签值信息导入模板')">
        <el-table :data="uploadTable" style="width: 100%" ref="dialogTableRef" id="upload-table">
            <!-- <el-table-column type="selection" width="50" v-if="selectShow"/> -->
            <el-table-column fixed prop="V_NUM" label="ID" width="70" />
            <el-table-column prop="VALUE" label="值" width="120" />
            <el-table-column prop="DESCRIPTION" label="描述" width="150" />
            <el-table-column prop="CUST_TYPE" label="类型" width="150" /> 
        </el-table>
    </Dialog>
</template>

<script setup>
import { ref, reactive } from 'vue'
import AdminSkeleton from '@/components/AdminSkeleton.vue';
import Paging from '@/components/Paging.vue'
import Control from '@/components/Control.vue'
import Dialog from '@/components/Dialog.vue'
import Drawer from '@/components/Drawer.vue'
import { getLbValuesInfo, editLbValueInfo, editManyLbValueInfo } from '@/utils/lpsApi/lb_values'
import { paging } from '@/utils/paging'
import { exportClickFromTableId, exportClickFromDatas } from '@/utils/downloadExcel'
import { objCopy } from '@/utils/objCopy'
import { msgOpen } from '@/utils/msg'
import { confirm, confirmBatch } from '@/utils/confirm'
import { lpsStore } from '@/stores/lpsStore'

const  useLpsStore = lpsStore()


//权限对象--用于控制按钮显示
const componentName = 'Lb_value'
const permObj = {
    add: { name: componentName, type: 'add' },
    update: { name: componentName, type: 'update' },
    delete: { name: componentName, type: 'delete' }
}


//#region 查询***********************************************************************************************************************
const {
    datasArr,
    datasLength,
    firstPage,
    pageSize,
    countPage,
    newDatasArr,
    btnDisabledObj,
    pagingPreprocessing,
    nextPage,
    lastPage,
    toFirstPage,
    toEndPage,
    toSpecifyPage,
    changePageSize
} = paging() //分页

// loading状态
let loading = ref(false);

//获取标签值列表
const getDatas = async () => {
    // console.log(useLpsStore.lbValInfo)
    loading.value = true;
    if(!useLpsStore.lbValInfo.length){
        const res = await getLbValuesInfo()
        useLpsStore.setLbValInfo(res.resDatas.result)
    }
    pagingPreprocessing(useLpsStore.lbValInfo)
    loading.value = false;
}
//#endregion********************************************************************************************************




//#region 编辑信息***************************************************************************************************
let title = ref("")
let size = ref("40%")
let formLabelWidth = ref("110")

//编辑用户信息
let drawerRef = ref(null) //组件ref
let oldLbValue = reactive({
    V_NUM: '',
    VALUE: '',
    DESCRIPTION: '',
    CUST_TYPE: ''
})
let editForm = reactive({
    V_NUM: '',
    VALUE: '',
    DESCRIPTION: '',
    CUST_TYPE: ''
})
//提交类型
let submitType = ref('')
//表单验证ref
let updateFormRef = ref(null)
//输入框验证规则
let rules = reactive({
    // V_NUM: [
    //     { required: true, message: '请输入ID', trigger: 'blur' }
    // ],
    VALUE: [
        { required: true, message: '请输入值', trigger: 'blur' }
    ],
    DESCRIPTION: [
        { required: true, message: '请输入描述', trigger: 'blur' }
    ],
    CUST_TYPE: [
        { required: true, message: '请输入类型', trigger: 'blur' }
    ]
})

//重置表单
const resetForm = () => {
    if (submitType.value === 'update' || submitType.value === 'copy') {
        editForm = objCopy(oldLbValue, editForm)
    } else if (submitType.value === 'add') {
        editForm = reactive({
            V_NUM: "",
            VALUE: "",
            DESCRIPTION: "",
            CUST_TYPE: ""
        })
    }
}

/**
 * 处理单个设备编辑、删除
 * @param type 操作类型，add：新增，update：编辑，del：删除
 * @param row 
 */
const editDatas = (type, row) => {
    // console.log(type)
    // console.log(row)
    submitType.value = type
    if (type === 'update') {
        drawerRef.value.open()
        title.value = "编辑"
        editForm = row
        //存储未修改前用户信息
        oldLbValue = objCopy(row, oldLbValue)
    }
    if (type === 'add') {
        drawerRef.value.open()
        title.value = "新增"
        resetForm()
    }
    if (type === "copy") {
        drawerRef.value.open()
        title.value = "复制"
        editForm = objCopy(row, editForm)
        editForm.V_NUM = ""
        editForm.DESCRIPTION += "_副本"
    }
}
//#endregion********************************************************************************************************




//#region 批量处理***************************************************************************************************
let batchIsShow = ref(false) //展示批量上传、批量删除状态
let selectShow = ref(false) //展示批量勾选状态
let selectRows = ref([]) //选中的设备行数据
let dialogRef = ref(null) //组件ref
let uploadKeys = ref([
    "V_NUM",
    "VALUE",
    "DESCRIPTION",
    "CUST_TYPE",
]) //上传的字段

const batchEdit = () => {
    if (newDatasArr.value.length) selectShow.value = !selectShow.value
    batchIsShow.value = !batchIsShow.value
}

/**
 * 表格选中行数据变化时触发的方法
 * @param val 选中的设备行数据
 */
const handleSelectionChange = (val) => {
    selectRows.value = val
}

//批量上传
let uploadTable = ref([])
const batchUpload = () => {
    // console.log('batchUpload');
    dialogRef.value.open()
}

//关闭
const closeDialog = () => {
    uploadTable = ref([])
    dialogRef.value.close()
}

//接收子组件传递的excel数据，渲染至界面
let dialogTableRef = ref(null)
const uploadFile = (e) => {
    // console.log(e.value)            
    uploadTable = e.value
}

//下载
let downloadBoxShow = ref(false) //展示下载框状态
const showDownloadBox = () => {
    downloadBoxShow.value = !downloadBoxShow.value
}
/** 
 * 下载当前页
 * @param {Array} data 导出的数据数组对象
 * @param {String} tableId table标签的ID
 * @param {String} fileName 需要命名的文件名
 */
const downloadExcelPaging = (data, tableId, fileName) => {
    data.length ? exportClickFromTableId(tableId, fileName) : msgOpen("无数据可供下载，请先查询数据")
}
/**
 * 下载全部
 * @param {Array} data 导出的数据数组对象(未进行分页)
 * @param {String} fileName 需要命名的文件名
 */
const downloadExcelAll = (data, fileName) => {
    if (data.length) {
        let newData = JSON.parse(JSON.stringify(data)) //深拷贝      
        exportClickFromDatas(newData, fileName)
    } else {
        msgOpen("无数据可供下载，请先查询数据")
    }
}

/**
 * 导入模版下载
 * @param tableId table标签的ID
 * @param fileName 需要命名的文件名
 */
const downloadTemplate = (tableId, fileName) => {
    // console.log(tableId)
    exportClickFromTableId(tableId, fileName)
}
//********************************************************************************************************************** */
//#endregion


/**
 * 处理值编辑、删除、批量操作
 * @param type 操作类型，batchDel：批量删除
 * @param data 选中的值数据
 * 
 */
const editSubmit = async (type, data) => {
    console.log(type)
    console.log(data)
    if(type === 'add' || type === 'update' || type === 'copy'){
        updateFormRef.value.validate(async (valid) => {
            if(!valid){
                return false
            }else{
                let res = await editLbValueInfo(type,data)
                console.log(res)
                drawerRef.value.hideLoading()
                drawerRef.value.close()
                res.status ? msgOpen(res.msg,'success') : msgOpen(res.msg)
                getDatas()
                resetForm() 
            }
        })       
    }
    if(type === 'delete'){
        let res = await confirm(data.V_NUM)
        if(res){
            let res = await editLbValueInfo(type,data)
            res.status ? msgOpen(res.msg,'success') : msgOpen(res.msg)
            getDatas()
        }
    }
    if(type === 'batchAdd' || type === 'batchUpdate'){
        let rowsArr = ref([]) 
        let editBatchStatus = ref(true)
        for(let i = 0;i < data.length;i++){
            console.log(data[i]);            
            if(type === 'batchUpdate' && !data[i].V_NUM){
                msgOpen("更新值，请填写V_NUM！")
                editBatchStatus.value = false
                break
            }else if(type === 'batchAdd' && data[i].V_NUM){
                msgOpen("新增值，V_NUM请留空！")
                editBatchStatus.value = false
                break  
            }else{
                rowsArr.value.push(data[i])
            }
        } 
        if(editBatchStatus.value){
            let res = await editManyLbValueInfo(type,rowsArr.value)
            // console.log(res)            
            dialogRef.value.close()
            uploadTable = ref([])
            if(!res.status){
                msgOpen(res.msg)
            }else{
                res.resDatas.result.rowsAffected ? msgOpen(`${res.msg},共${res.resDatas.result.rowsAffected}条`,"success") 
                                                            : msgOpen(res.msg)
            }    
            getDatas() 
        }
    } 
    if(type === 'batchDel'){
        if(!data.length){
            msgOpen('未进行勾选，请勾选！')
        }else{
            let isDel = await confirmBatch(data.length) 
            if(isDel){
                let vNumArr = []
                data?.forEach(item => {
                    let arr = []
                    arr.push(item.V_NUM) 
                    vNumArr.push(arr)
                })
                let res = await editManyLbValueInfo(type,vNumArr) 
                if(!res.status){
                    msgOpen(res.msg)
                }else{
                    res.resDatas.result.rowsAffected ? msgOpen(`${res.msg},共${res.resDatas.result.rowsAffected}条`,"success") 
                                                                : msgOpen(res.msg)
                }        
                getDatas() 
            }
        }
    }  
}
//#endregion

</script>

<style lang="less" scoped>
.params {
    width: 100%;
    height: 100%;

    .el-form {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: flex-start;

        .el-form-item {
            margin-bottom: 0;
            margin-right: .3125rem;
        }
    }

}

.el-table {
    height: 95%;
}
</style>